
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>WebSocket</title>
    <script type="text/javascript" src="socket.io.js"></script>
</head>
<body>
<h1> socket.io Client</h1>
<input id="sendTxt" type="text"/>
<button id="sendBtn">发送</button>
<div id="recv"></div>
<script type="text/javascript">

    var socket = io("ws://localhost:8000?uid=zhangsan");

    //把接收的数据显示到界面
    function showMessage(str){
        var div = document.createElement('div');
        div.innerHTML = str;
        document.body.appendChild(div)
    }

    // 点击之后发送
    document.getElementById("sendBtn").onclick = function(){
        var txt = document.getElementById("sendTxt").value;
        if(txt){        // 文本不为空发送
            socket.emit('notice',txt);
        }
    }

    // 连接成功
    socket.on('connect', function(socket){
        showMessage("连接成功")
    });

    // 连接失败
    socket.on('disconnect', function(socket){
        showMessage("连接失败")
    });

    socket.on('error', function(socket){
        showMessage("连接错误")
    });

    socket.on('notice',function(data){
        console.log("receive server data",data);
        showMessage(data)
    })
</script>
</body>
</html>